package com.holystone.orca.itsm.system.util;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Copyright (c) 2018, BEYONDWINET Technologies, Inc.
 * All right reserved.
 *
 * @author qijunxing
 * @desc:把 list集合 按照 谋个属性进行分组
 * @date 2018年2月5日上午11:34:33
 */
public class ListToMapUtil {

    /**
     * List转Map
     * @param list 集合
     * @param keyFieldGetMethodName 作为Map-key的字段get方法名称，该字段的值具有唯一性
     * @param <K> 集合中的对象
     * @return Map<String, K> key为属性值
     */
    public static <K> Map<String, K> ListToMap(List<K> list, String keyFieldGetMethodName) {
        Map<String, K> result = new HashMap<>();
        if (null == list || list.size()==0|| null == keyFieldGetMethodName || keyFieldGetMethodName.equals("")) {
            return result;
        }

        try {
            Method methodGetKey = list.get(0).getClass().getMethod(keyFieldGetMethodName);
            for (int i = 0; i < list.size(); i++) {
                K obj = list.get(i);
                String key = methodGetKey.invoke(obj)+"";
                result.put(key, obj);
            }
        } catch (Exception e) {
            throw new IllegalArgumentException("field can't match the key!");
        }

        return result;
    }
}
